import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/base/page_constance.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/dv_entity.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/modle/main/entity/id_name_entity.dart';
import 'package:shopping_group/modle/person/entity/cust_bankInfo_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';
import 'package:shopping_group/utils/utils.dart';

class BankListBloc implements BlocBase {
  List<CustBankInfoEntity> _listEntity = [];

  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  StreamController<Object> _allController = StreamController<Object>();
  StreamSink get _addDate => _allController.sink;
  Stream<Object> get sendData => _allController.stream;

  StreamController<Object> _bankTypeController = StreamController<Object>();
  StreamSink get bankTypeDate => _bankTypeController.sink;

  StreamController<Object> _getBankTypeController = StreamController<Object>();
  StreamSink get _addBankTypeDate => _getBankTypeController.sink;
  Stream<Object> get sendBankTypeData => _getBankTypeController.stream;

  StreamController<Object> _addBankController = StreamController<Object>();
  StreamSink get addBankDate => _addBankController.sink;

  StreamController<Object> _deleteController = StreamController<Object>();
  StreamSink get deleteDate => _deleteController.sink;

  StreamController<Object> _txController = StreamController<Object>();
  StreamSink get txDate => _txController.sink;

  StreamController<Object> _fljtxController = StreamController<Object>();
  StreamSink get fljtxDate => _fljtxController.sink;

  StreamController<Object> _jttxController = StreamController<Object>();
  StreamSink get jttxDate => _jttxController.sink;

  StreamController<Object> _kytxController = StreamController<Object>();
  StreamSink get kytxDate => _kytxController.sink;

  BankListBloc() {
    _initController.stream.listen(initData);
    _bankTypeController.stream.listen(bankTypeData);
    _addBankController.stream.listen(addBankData);
    _deleteController.stream.listen(deleteData);
    _txController.stream.listen(txData);
    _fljtxController.stream.listen(fljtxData);
    _jttxController.stream.listen(jttxData);
    _kytxController.stream.listen(kytxData);
  }

  void kytxData(data) {
    if (data is Map) {
      _kytxTask(data);
    }
  }

  void jttxData(data) {
    if (data is Map) {
      _jttxTask(data);
    }
  }

  void fljtxData(data) {
    if (data is Map) {
      _fljtxTask(data);
    }
  }

  void txData(data) {
    if (data is Map) {
      _txTask(data);
    }
  }

  void deleteData(data) {
    if (data is Map) {
      _deleteTask(data);
    }
  }

  void addBankData(data) {
    if (data is Map) {
      _addBankTask(data);
    }
  }

  void bankTypeData(data) {
    _getBankTypeTask();
  }

  void initData(data) {
    Future.wait([
      _initTask(),
      _getBankTypeTask(),
    ]);
  }

  Future _kytxTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    // BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.KY_TX_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            SvEntity entity = SvEntity.fromJson(result);
            eventBus.fire(MaxMoneyEvent(entity.val));
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _jttxTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.JT_TX_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            BotToast.showText(text: '提现成功');
            eventBus.fire(RefreshEvent());
            eventBus.fire(ResetMoneyEvent());
            RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _fljtxTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.FLJ_TX_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            BotToast.showText(text: '提现成功');
            eventBus.fire(RefreshEvent());
            eventBus.fire(ResetMoneyEvent());
            RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _txTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.BANK_TX_URL_NEW, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            BotToast.showText(text: '提现成功');
            eventBus.fire(RefreshEvent());
            eventBus.fire(ResetMoneyEvent());
            RouteUtil.popUntil(PageConstance.MAIN_PAGE);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _deleteTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.BANK_DELETE_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            eventBus.fire(RefreshEvent());
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _addBankTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.BANK_ADD_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            eventBus.fire(RefreshEvent());
            RouteUtil.closeView();
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _getBankTypeTask() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    if (!ObjectUtil.isEmptyList(BaseConstant.bankTypeList)) {
      _addBankTypeDate.add(BaseConstant.bankTypeList);
      return;
    }
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.BANK_TYPELIST_URL, data: {}, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            List list = List.from(result);
            list.forEach((element) {
              BaseConstant.bankTypeList.add(IdNameEntity.fromJson(element));
            });
            BaseConstant.bankTypeList.forEach((bankEntity) {
              if (bankEntity.name.contains('支付宝')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/1.png';
              } else if (bankEntity.name.contains('中国银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/15.png';
              } else if (bankEntity.name.contains('建设银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/3.png';
              } else if (bankEntity.name.contains('工商银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/4.png';
              } else if (bankEntity.name.contains('农业银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/6.png';
              } else if (bankEntity.name.contains('招商银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/5.png';
              } else if (bankEntity.name.contains('邮政储蓄')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/13.png';
              } else if (bankEntity.name.contains('兴业银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/11.png';
              } else if (bankEntity.name.contains('光大银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/7.png';
              } else if (bankEntity.name.contains('广发银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/8.png';
              } else if (bankEntity.name.contains('交通银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/9.png';
              } else if (bankEntity.name.contains('平安银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/10.png';
              } else if (bankEntity.name.contains('民生银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/12.png';
              } else if (bankEntity.name.contains('中信银行')) {
                bankEntity.imageUrl =
                    'https://static.jiujiupingou.com/Static/img/banklogo/14.png';
              } else {
                bankEntity.imageUrl =
                    'https://lizhengyouxuan.oss-cn-shanghai.aliyuncs.com/lizhengyouxuan/other/zutp.png';
              }
            });
            BaseConstant.bankTypeMap = Utils.toMap(BaseConstant.bankTypeList);
            _addBankTypeDate.add(BaseConstant.bankTypeList);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  Future _initTask() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    Map<String, dynamic> data = {};
    data['val'] = BaseConstant.userId;
    // data['pageIndex'] = pageNo;
    // data['pageSize'] = BaseConstant.PAGE_SIZE;
    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.BANK_LIST_URL, data: data, headers: {},
            success: (result) {
          _listEntity?.clear();
          BotToast.closeAllLoading();
          if (null != result) {
            List list = List.from(result);
            list.forEach((element) {
              _listEntity.add(CustBankInfoEntity.fromJson(element));
            });
            _addDate.add(_listEntity);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
    _fljtxController?.close();
    _allController?.close();
    _bankTypeController?.close();
    _getBankTypeController?.close();
    _addBankController?.close();
    _txController?.close();
    _deleteController?.close();
    _jttxController?.close();
    _kytxController?.close();
  }
}
